package com.example.controller;

import com.example.entity.Role;
import com.example.entity.example.RoleExample;
import com.example.service.RoleService;
import com.example.util.ResultEntity;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @PreAuthorize("hasRole('ROLE_3') ")
    @ResponseBody
    @RequestMapping("/get/all/roles.json")
    public ResultEntity<List<Role>> getAllDepts(@RequestParam("page") Integer page,
                                                @RequestParam("limit") Integer limit,
                                                @RequestParam(value = "id", required = false) Integer id,
                                                @RequestParam(value = "name", required = false) String name
    ) {
        RoleExample example = new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria();
        if (id != null) {
            criteria.andRidEqualTo(id);
        }
        if (name != null && !name.isEmpty()) {
            criteria.andRnameLike("%" + name + "%");
        }
        List<Role> allDepts = roleService.getByExampleWithLimit(example, page, limit);
        int count = (int)roleService.getCountByExample(example);
        return ResultEntity.createResultEntity(0, null, count, allDepts);
    }

    @PreAuthorize("hasRole('ROLE_3')")
    @RequestMapping("/add/page.html")
    public String addPage(){
        return "include/add-role";
    }

    @PreAuthorize("hasRole('ROLE_3')")
    @ResponseBody
    @RequestMapping("/add")
    public ResultEntity<Object> addRole(@RequestBody Role role) {
        roleService.addRole(role);
        return ResultEntity.createResultEntity(0, null, 0, null);
    }

    @PreAuthorize("hasRole('ROLE_3')")
    @ResponseBody
    @RequestMapping("/remove")
    public ResultEntity<Object> removeById(@Param("id") Integer id) {
        try {
            roleService.removeById(id);
        } catch (Exception e) {
            return ResultEntity.createResultEntity(-1, e.getMessage(), 0, null);
        }
        return ResultEntity.createResultEntity(0, null, 0, null);
    }

    @PreAuthorize("hasRole('ROLE_3')")
    @ResponseBody
    @RequestMapping("/update")
    public ResultEntity<Object> updateById(@RequestBody Role role) {
        try {
            roleService.updateById(role);
        } catch (Exception e) {
            return ResultEntity.createResultEntity(-1, e.getMessage(), 0, null);
        }
        return ResultEntity.createResultEntity(0, null, 0, null);
    }
}
